package com.bihucms.ssm.util;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

/**
 * Created by benhailong on 2017/10/4.
 */
public class WebSettingUtil {

    public static void main(String[] args) {
        String path = "src/main/resources/webseting.properties";
        // 读取文件
        Map<String,String> webset = read(path);
        System.out.println("读取到的："+webset.get("yan"));

        // 写入配置文件
//        Map<String,String> webset = new HashMap<String,String>();
//        webset.put("yyy","111");
//        webset.put("xxx","222");
//        webset.put("zzz","333");
//
//        write(webset,path,"这里是备注");


    }

    // 读取文件
    public static Map<String,String> read(String path){

        Map<String,String> webset = new HashMap<String,String>();

        Properties prop = new Properties();
        try{
            //读取属性文件a.properties
            InputStream in = new BufferedInputStream (new FileInputStream(path));
            prop.load(in);     ///加载属性列表
            Iterator<String> it = prop.stringPropertyNames().iterator();
            while(it.hasNext()){
                String key=it.next();
                webset.put(key,prop.getProperty(key));
            }
            in.close();
        }
        catch(Exception e){
            System.out.println(e);
        }
        return webset;
    }

    // 修改
    // 必须把原有的参数全部带全，否则会出现读取错误
    public static void write(Map<String,String> map,String path,String note){
        Properties prop = new Properties();
        try{
            ///保存属性到 配置文件
            FileOutputStream oFile = new FileOutputStream(path, false);//true表示追加打开 false标识重写
            for (Map.Entry<String,String> entry : map.entrySet()) {
                prop.setProperty(entry.getKey(),entry.getValue());
            }
            prop.store(oFile, note);
            oFile.close();
        }
        catch(Exception e){
            System.out.println(e);
        }
    }

}
